package com.demo.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.aop.AuthorizationRequired;
import com.demo.core.constants.HttpStatus;
import com.demo.core.domain.Result;
import com.demo.core.exception.BusinessException;
import com.demo.core.exception.ParameterException;
import com.demo.domain.PracticalAchievement;
import com.demo.domain.PracticalAchievementFile;
import com.demo.domain.TeamComposition;
import com.demo.domain.ro.AchievementSearchRequest;
import com.demo.service.FileService;
import com.demo.service.PracticalAchievementService;
import com.demo.utils.DownLoadZipUtil;
import com.demo.utils.PageBean;
import com.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/achievement")
public class PracticalAchievementController {
    @Autowired
    private PracticalAchievementService practicalAchievementService;

    @Autowired
    private FileService fileService;

    //文件磁盘路径
    @Value("${file.location}")//配置文件设定的自定义路径
    private String fileUploadPath;

    /**
     * 根据类型和分页信息得到所有实践成果
     *
     * @param searchRequest
     * @param request
     * @return
     * @throws Exception
     */
   @AuthorizationRequired
    @PostMapping("/getAllAchievement")
    public Result getAllAchievement(@RequestBody AchievementSearchRequest searchRequest, HttpServletRequest request) throws Exception {
        if (searchRequest == null
                || searchRequest.getType() == null
                || searchRequest.getType() < 0 || searchRequest.getType() > 4
                || searchRequest.getCurrentPage() <= 0
                || searchRequest.getPageSize() <= 0) {
            throw new ParameterException("有必要属性为空");
        }
        if (request == null) {
            throw new ParameterException("request为空");
        }
        Long uid = (Long) request.getAttribute("userId");
        Page<PracticalAchievement> page=
                practicalAchievementService
                        .getAllAchievement(searchRequest.getType(), searchRequest.getCurrentPage(), searchRequest.getPageSize(), uid);
        return page == null||page.getRecords().size()<0?
                Result.success(HttpStatus.SUCCESS, "无相关信息", new Page<>()):
                Result.success(HttpStatus.SUCCESS, "查询成功", page);
    }

    /**
     * 根据项目等级查询所有项目成果
     *
     * @param searchRequest
     * @param request
     * @return
     * @throws Exception
     */
    @AuthorizationRequired
    @PostMapping("/level/all")
    public Result getAllByLevel(@RequestBody AchievementSearchRequest searchRequest, HttpServletRequest request) throws Exception {
        if (searchRequest == null) {
            throw new ParameterException("有必要属性为空");
        }
        Long uid = (Long) request.getAttribute("userId");
        List<PracticalAchievement> results = practicalAchievementService.getAllByLevel(searchRequest, uid);
        return Result.success(HttpStatus.SUCCESS, "查询成功", results);
    }

    /**
     * 搜索实践成果
     * @param searchRequest
     * @param request
     * @return
     * @throws Exception
     */
    @AuthorizationRequired
    @PostMapping("/search")
    public Result searchAchievements(@RequestBody AchievementSearchRequest searchRequest, HttpServletRequest request) throws Exception {
        if(searchRequest == null) {
            throw new BusinessException(HttpStatus.PARAMS_ERROR, "参数异常");
        }
        Long uid = (Long) request.getAttribute("userId");
        if(uid == null) {
            throw new BusinessException(HttpStatus.NOT_LOGIN, "用户未登录");
        }
        searchRequest.setUid(uid);
        // 搜索
        Page<PracticalAchievement> page = practicalAchievementService.searchAchievements(searchRequest);
        return Result.success(HttpStatus.SUCCESS,"查找成功",page);
    }


    /**
     * 得到某个实践成果的详细介绍（不实现模糊搜索）
     *
     * @param searchRequest
     * @param request
     * @return
     * @throws Exception
     */
    @AuthorizationRequired
    @PostMapping("/getAnAchievement")
    public Result getAnAchievement(@RequestBody AchievementSearchRequest searchRequest, HttpServletRequest request) throws Exception {
        if (request == null) {
            throw new ParameterException("request为空");
        }
        Long uid = (Long) request.getAttribute("userId");
        if (searchRequest != null && uid != null && uid > 0l) {
            searchRequest.setUid(uid);
            PracticalAchievement achievement = practicalAchievementService.getAchievement(searchRequest);
            return achievement!=null?
                    Result.success(HttpStatus.SUCCESS,"查找成功",achievement):
                    Result.success(HttpStatus.SUCCESS,"无相关信息",null);
        }
        return Result.success(HttpStatus.BAD_REQUEST,"搜索失败，请联系管理员重新尝试",new Page<>());
    }

    /**根据请求得到uid（根据token）
     *
     * @param request
     * @return
     * @throws ParameterException
     */
//    public Long getUid(HttpServletRequest request) throws ParameterException {
//        // 获取用户的token进而获取当前用户的uid
//        String token = request.getHeader("token");
//        if (token == null || token.equals("")) {
//            System.out.println("token为空");
//            return null;
//        }
//        return userController.decTokenController(token);
//    }
//

    @AuthorizationRequired
    @PostMapping(value = "/exportExcelAll")
    @Operation(summary = "导出文件", description = "导出记录")
    @Parameter(required = false)
    public void exportExcel(HttpServletRequest request, HttpServletResponse response, @RequestBody List<Long> ids) throws Exception {
        if (request == null) {
            throw new ParameterException("request为空");
        }
        Long uid = (Long) request.getAttribute("userId");
        if (ids != null) {
            Boolean flag = practicalAchievementService.isAchievementEmpty(uid, ids);
            if (flag == true) {
                practicalAchievementService.exportExcel(request, response, ids);
            }
        }
    }

    /**
     * 新增实践成果
     *
     * @param practicalAchievement
     * @param files
     * @return
     * @throws Exception
     */
    @PostMapping("/importAchievementAndFile")
    public Result importAchievementAndFile(PracticalAchievement practicalAchievement, @RequestParam(
            value = "files") MultipartFile files[]) throws Exception {
//        String possessorId = getPossessorId(request);
        boolean result = practicalAchievementService.importAchievementAndFile(practicalAchievement, files);
        if (result == true) {
            return Result.success("新增实践成果成功！");
        }
        return Result.error("新增实践成果失败，请联系管理员重新尝试");
    }


    /**
     * 下载压缩包文件
     *
     * @param paId
     * @param response
     * @param request
     * @return
     */
    /**
     * 下载压缩包文件
     *
     * @param paId
     * @param response
     * @param request
     * @return
     */
    @RequestMapping(path = "/downloadZip", method
            = {RequestMethod.GET, RequestMethod.POST})
    public Result zipFileDownLoad(@RequestParam("paId") int paId,
                                HttpServletResponse response, HttpServletRequest request) {
        //通过paid获取url
        List<PracticalAchievementFile> fileUrlByPaid = fileService.findFileByPaId(paId);
        System.out.println(fileUrlByPaid);

        //创建集合存储url和fileName
        List<Map<String, String>> mapList = new ArrayList<>();
        for (PracticalAchievementFile paFile : fileUrlByPaid) {
            Map<String, String> map = new HashMap<>();
            //获取文件的url
            String urlStr = paFile.getFUrl();
            //获取文件编码后的名字
            String fileNewName = urlStr.substring(urlStr.lastIndexOf("/"));
            map.put("path", urlStr);
            map.put("name", fileNewName);
            //向集合中添加url
            mapList.add(map);
        }
//        if (mapList.isEmpty() == true) {
//            // fixme: 不存在附件是本来就没有，还是查询失败，是否可以返回空压缩包
//            throw new NullPointerException("mapList中需要下载的文件为空");
//        }
        //获取实践成果名称给压缩包命名
        String packageName =
                practicalAchievementService.getTitleById(paId) + new SimpleDateFormat(
                        "_yyyy-MM-dd_HH:mm:ss").format(new Date()) + ".zip";
        //调用压缩文件方法
        boolean result =
                DownLoadZipUtil.zipUrlToFile(mapList, packageName, request, response);
        if (result == true) {
            return Result.success("下载文件成功！");
        }
        return Result.success("下载错误，请联系管理员。");
    }

    /**
     * 搜索实践成果-多项查询
     * @param practicalAchievement
     * @param practicalAchievement
     * @return
     * @throws Exception
     */
//    @AuthorizationRequired
    @GetMapping("/page")
    @Operation(summary="分页搜索")
    public Result page(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize")Integer pageSize,
                       PracticalAchievement practicalAchievement) throws ParameterException {
        List<PracticalAchievement> list = null;
        PageBean<PracticalAchievement> info = new PageBean<>();
        if(practicalAchievement.getTitle()!=null || practicalAchievement.getAdvisorName()!=null || practicalAchievement.getPossessorName() != null){
            list = practicalAchievementService.selectPracticalAchievementList(practicalAchievement);
        }else{
            list = practicalAchievementService.listAllPracticalAchievement();
        }
        System.out.println("list"+list);
        PageInfo<PracticalAchievement> pageInfo = new PageInfo<>(list);
        int total = (int)pageInfo.getTotal();
        int startIndex = (pageNum -1)*pageSize;
        int endIndex = Math.min(startIndex + pageSize,total);
        List<PracticalAchievement> pageList = list.subList(startIndex,endIndex);
        info.setPageList(pageList);
        info.setPageNumber(pageNum);
        info.setPageSize(pageSize);
        info.setTotal(total);
        info.setTotalPage((total+pageSize-1)/pageSize);
        return Result.success(info);
    }

    @Operation(summary="修改实践成果")
    @PostMapping("/edit")
    public Result edit(@RequestBody PracticalAchievement practicalAchievement,HttpServletRequest request) throws ParameterException {
        int rows = practicalAchievementService.updatePracticalAchievement(practicalAchievement);
        return rows > 0 ? Result.success("修改实践成果成功"):Result.error("修改实践成果失败");
    }

    @Operation(summary="删除实践成果")
    @PostMapping ("/delete")
    public Result remove(@RequestBody List<PracticalAchievement> practicalAchievements,HttpServletRequest request) throws ParameterException {
        int row = 0;
        int length = practicalAchievements.size();
        for(PracticalAchievement practicalAchievement:practicalAchievements){
            row += practicalAchievementService.deletePracticalAchievementById(practicalAchievement);
        }
        return row ==length ? Result.success("删除实践成果成功") : Result.error("删除实践成果失败");
    }
}
